//
//  NSObject+Cache.m
//  iOS_ChenQiang
//
//  Created by 陈强 on 16/5/18.
//  Copyright © 2016年 chenqiang1202. All rights reserved.
//

#import "NSObject+Cache.h"

@implementation NSObject (Cache)
//计算文件的大小
+ (float)fileSizePath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }
    return 0;
}

//计算缓存文件夹的大小
+ (NSString *)calculateCache {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float folderSize = 0.f;
    if ([fileManager fileExistsAtPath:path]) {
        //拿到有文件的数组
        NSArray *childerFile = [fileManager subpathsAtPath:path];
        //拿到每个文件的名字 如果不想清除某个文件 就在这里判断
        for (NSString *fileName in childerFile) {
            //将路径拼接到一起
            NSString *fullPath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizePath:fullPath];
        }
    }
    NSString *sizeStr = folderSize >= 1024*1024?[NSString stringWithFormat:@"%.2fMB",folderSize/1024.0/1024.0]:[NSString stringWithFormat:@"%.2fKB",folderSize/1024.0];
    return sizeStr;
}

//清除缓存
+ (void)removedCache {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        //拿到有文件的数组
        NSArray *childerFile = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFile) {
            //加入条件 过滤掉不想删除的文件
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}
@end
